package work.lrl.coupon_send;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import core.util.TransformCsvData;
import io.netty.channel.nio.NioEventLoopGroup;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import work.gac.unbind.v2.MemberUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 收集用户阶段 如果用户已经确认可以跳过该阶段
 */
@Slf4j
public class Demo {
    @SneakyThrows
    public static void main(String[] args) {
        List<String> userThiIds = new ArrayList<>();
        TransformCsvData.peekCsv(Setting.readFIle, 1, s -> {
            if (StrUtil.isNotBlank(s[0])) {
                userThiIds.add(s[0]);
            }
        });
        List<ExcelObject> result = new CopyOnWriteArrayList<>();
        //收集用户ID
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        AtomicInteger count = new AtomicInteger();
        log.info("【卡券群发】开始收集用户");
        for (String userThiId : userThiIds) {
            eventExecutors.execute(() -> {
                if (count.getAndIncrement() % 2000 == 0) {
                    log.info("【卡券群发】用户收集 进度 ->{}", count.get());
                }
                JSONObject customer = MemberUtil.getCustomerByID(userThiId, Setting.baseUrl, Setting.token);
                if (Objects.isNull(customer)) {
                    result.add(
                            ExcelObject.builder()
                                    .thiId(userThiId)
                                    .hit("否")
                                    .build()
                    );
                    return;
                }
                result.add(
                        ExcelObject.builder()
                                .thiId(userThiId)
                                .customerId(customer.getStr("id"))
                                .name(customer.getJSONObject("basicInfo").getStr("realName"))
                                .hit("是").build()
                );
            });
        }
        eventExecutors.shutdownGracefully().sync();
        EasyExcel.write(Setting.setup1, ExcelObject.class).sheet("sheet1").doWrite(result);
        log.info("【卡券群发】用户收集完毕 size->{}", result.size());
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    @ColumnWidth(value = 20)
    public static class ExcelObject {
        @ExcelProperty("三方卡号")
        private String thiId;
        @ExcelProperty("用户ID")
        private String customerId;
        @ExcelProperty("用户姓名")
        private String name;
        @ExcelProperty("是否找到")
        private String hit;
        @ExcelProperty("是否成功发放")
        private String success;

        @ExcelProperty("错误内容")
        private String errMsg;
    }

}
